/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-use-before-define */
import { DictValueEnum } from "@/components/DictTag";
import { getDictType } from "@/services/api/module/tenant/developer/dictType";
// @ts-ignore
import { ModalForm, ProFormInstance, ProFormSelect, ProFormText, ProFormTextArea } from "@ant-design/pro-components";
// @ts-ignore
import React, { useEffect, useRef, useState } from "react";
import { formTitle } from "../constants";
export type DictTypeParams = Record<string, unknown> & Partial<API.System.DictType>;

export type DictTypeFormProps = {
	onCancel: (flag?: boolean) => void;
	onSubmit: (values: DictTypeParams) => Promise<any>;
	open: boolean;
	dictCategory: DictValueEnum | any;
	id: number | undefined;
};
const DictTypeForm: React.FC<DictTypeFormProps> = props => {
	const formRef = useRef<ProFormInstance>();
	const { id, open, onCancel, dictCategory, onSubmit } = props;
	useEffect(() => {
		if (id) {
			setFormValue(id);
		}
	}, [id]);

	// 表单赋值
	const setFormValue = (id: number) => {
		getDictType(id).then(data => {
			formRef?.current?.setFieldsValue(data);
		});
	};
	// 关闭表单
	const handleCancel = () => {
		// 表单重置
		formRef?.current?.resetFields();
		onCancel();
	};
	// 提交表单
	const handleFinish = async (values: DictTypeParams) => {
		return onSubmit({ ...(values as DictTypeParams), ...{ id: id ? id : undefined } });
	};

	return (
		<ModalForm<DictTypeParams>
			width={400}
			title={id ? formTitle[1] : formTitle[0]}
			open={open}
			autoFocusFirstInput
			formRef={formRef}
			grid={true}
			layout="vertical"
			onFinish={handleFinish}
			modalProps={{
				destroyOnClose: true,
				onCancel: () => {
					handleCancel();
				}
			}}
		>
			<ProFormSelect
				name="category"
				label="所属分类"
				rules={[{ required: true, message: "请选择字典类型" }]}
				valueEnum={dictCategory}
				placeholder="请选择字典分类"
			/>
			<ProFormText
				name="dictName"
				label="字典名称"
				placeholder="请输入字典名称"
				rules={[
					{
						required: true,
						message: "请输入字典名称"
					}
				]}
			/>
			<ProFormText
				name="dictType"
				label="字典编码"
				placeholder="请输入字典编码"
				rules={[
					{
						required: true,
						message: "字典编码为必填项"
					},
					{
						pattern: /^[A-Za-z_]+$/,
						message: "输入字典编码有误，只允许英文加下划线"
					}
				]}
			/>
			<ProFormTextArea name="remark" label="备注" placeholder="请输入备注" />
		</ModalForm>
	);
};

export default DictTypeForm;
